package com.study.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WsServerInitializer extends ChannelInitializer<SocketChannel> {
    protected void initChannel(SocketChannel sc) throws Exception {
        ChannelPipeline pipeline = sc.pipeline();
        ///////////////  用于支持http协议  ////////////////
        //Websocket基于http协议,在此添加http编解码器
        pipeline.addLast(new HttpServerCodec());
        //添加对大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //对HttpMessage进行聚合,聚合为FullHttprequset或FullHttpresponse
        //几乎在netty中的编程,都会使用到此Handler
        pipeline.addLast(new HttpObjectAggregator(1024*64));

        ///////////////  websocket协议  ///////////////
        /**
         * websocket服务器处理协议,用于制定给客户端连接访问路由: /ws
         * 本handler会帮我们处理一些复杂的事情
         * 处理动作有: handshaking(close,ping,pong) ping+pong=心跳
         * 对于wensocket来讲,所有信息都是以frames来传输的,不同的数据类型对应不同frames
         */
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        // 自定义的handler
        pipeline.addLast(new ChatHandler());
    }
}
